package icu.lookyousmileface.netty.simple

import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.util.CharsetUtil

/**
 * @title: NettyClientHandler
 * @projectName NettyPro
 * @author shenj
 * @date 2020/12/4 1:52
 *继承自入栈适配器
 */
class NettyClientHandler: ChannelInboundHandlerAdapter() {
    /**
     * @author shenj
     * @title: channelActive
     * @date 2020/12/4  2:04
     * 客户端发送数据给服务器
     */
    override fun channelActive(ctx: ChannelHandlerContext?) {
        println("Client ctx:"+ctx)
        ctx?.writeAndFlush(Unpooled.copiedBuffer("Hi,Server!!!!", CharsetUtil.UTF_8))
    }
    /**
     * @author shenj
     * @title: channelRead
     * @date 2020/12/4  2:04
     * 接收服务器发送的数据并显示
     */
    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        val dataBuf = msg as ByteBuf
        println("服务器回复的信息："+dataBuf.toString(CharsetUtil.UTF_8))
        println("服务器地址："+ctx?.channel()?.remoteAddress())
    }
    /**
     * @author shenj
     * @title: exceptionCaught
     * @date 2020/12/4  2:11
     * 异常处理
     */
    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        cause?.printStackTrace()
        ctx?.close()
    }
}